package com.zq.ssmdemo.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import java.io.IOException;  
  
public class CharacterEncodingFilter implements Filter {  
  
    private String encoding = "UTF-8";  
  
    @Override  
    public void init(FilterConfig filterConfig) throws ServletException {  
        // 可以从配置文件中获取编码格式  
        String encodingParam = filterConfig.getInitParameter("encoding");  
        if (encodingParam != null) {  
            encoding = encodingParam;  
        }  
    }  
  
    @Override  
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  
            throws IOException, ServletException {  
        // 设置请求和响应的字符编码  
        if (request instanceof HttpServletRequest) {  
            HttpServletRequest httpRequest = (HttpServletRequest) request;  
            httpRequest.setCharacterEncoding(encoding);  
        }  
        if (response instanceof HttpServletResponse) {  
            HttpServletResponse httpResponse = (HttpServletResponse) response;  
            httpResponse.setContentType("text/html;charset=" + encoding);  
        }  
  
        // 继续过滤器链  
        chain.doFilter(request, response);  
    }  
  
    @Override  
    public void destroy() {  
        // 清理资源（如果有的话）  
    }  
}